import { _decorator, Component, Node,Animation, Graphics, Input, Contact2DType, Collider2D, SpriteFrame, Sprite, log} from 'cc';
import { TowerManager } from './TowerManager';
import { GameManager } from './GameManager';
import { Enemy } from './Enemy';
import { SoundManager } from './SoundManager';
const { ccclass, property } = _decorator;

//防御塔类型
enum TowerType {
    NONE,
    ARROW,
    BOMB
}

//防御塔配置 #33ff3333
const TOWER_CONFIG = {
    [TowerType.ARROW]: {
        range: 400,
        color: '#ff000033',
        // 其他属性...
    },
    [TowerType.BOMB]: {
        range: 400,
        color: '#ff000033',
        // 其他属性...
    }
}

@ccclass('Tower')
export class Tower extends Component {

    //攻击范围内的敌人
    enemies:Node[] = [];

    @property(Node)
    ringNode:Node = null;

    attackInterval:number = 1;

    attackTime:number = 0;

    //默认无类型
    type:TowerType = TowerType.NONE;

    //攻击范围
    attackRange:number = 100;


    //两种塔的升级按钮
    arrowBtnNode:Node = null;
    bombBtnNode:Node = null;

    //两种塔的攻击范围图
    arrowGraphics:Graphics = null;
    bombGraphics:Graphics = null;

    //两种塔的碰撞器
    arrowCollider:Collider2D = null;
    bombCollider:Collider2D = null;

    gameManager:GameManager = null;

    //士兵正面
    @property(SpriteFrame)
    soldierFront:SpriteFrame = null;

    //士兵反面
    @property(SpriteFrame)
    soldierBack:SpriteFrame = null;

    soldier1Animation:Animation = null;
    soldier2Animation:Animation = null;

    soundManager:SoundManager = null;

    start() {
        this.soundManager = SoundManager.instance;
        this.gameManager = GameManager.getInstance();

        if(this.ringNode){

            //塔升级选项节点
            this.arrowBtnNode = this.ringNode.getChildByName("Btn1");
            this.bombBtnNode = this.ringNode.getChildByName("Btn2");
    
            //触摸，停留，离开事件绑定
            this.arrowBtnNode.on(Input.EventType.TOUCH_START, this.showAttackRange, this);
            this.arrowBtnNode.on(Input.EventType.TOUCH_END, this.choiceArrowTower, this);
            this.arrowBtnNode.on(Input.EventType.TOUCH_CANCEL, this.hideAttackRange, this);
            this.bombBtnNode.on(Input.EventType.TOUCH_START, this.showAttackRange, this);
            this.bombBtnNode.on(Input.EventType.TOUCH_END, this.choiceBombTower, this);
            this.bombBtnNode.on(Input.EventType.TOUCH_CANCEL, this.hideAttackRange, this);

            //攻击范围图
            this.arrowGraphics = this.arrowBtnNode.getChildByName("Range").getComponent(Graphics);
            this.bombGraphics = this.bombBtnNode.getChildByName("Range").getComponent(Graphics);

        }

        //不同塔的不同触发事件
        switch(this.type){
            case TowerType.ARROW:
                this.arrowCollider = this.node.getComponent(Collider2D);
                this.arrowCollider.on(Contact2DType.BEGIN_CONTACT, this.onArrowContactEnter, this);
                this.arrowCollider.on(Contact2DType.END_CONTACT, this.onArrowContactEnd, this);
                this.attackInterval = 1;
                this.attackTime = 1;
                break;      
            case TowerType.BOMB:
                this.bombCollider = this.node.getComponent(Collider2D);
                this.bombCollider.on(Contact2DType.BEGIN_CONTACT, this.onBombContactEnter, this);
                this.bombCollider.on(Contact2DType.END_CONTACT, this.onBombContactEnd, this);
                this.attackInterval = 2;
                this.attackTime = 2;
                break;
        }
    }

    //箭塔碰撞
    onArrowContactEnter(selfCollider:Collider2D, otherCollider:Collider2D){

        var comp = otherCollider.node.getComponent(Enemy);
        
        //如果敌人不在攻击范围内，则添加到攻击范围内
        if(this.enemies.indexOf(otherCollider.node) == -1 && comp.HP > 0){
            this.enemies.push(otherCollider.node);
        }
    }

    //箭塔碰撞结束
    onArrowContactEnd(selfCollider:Collider2D, otherCollider:Collider2D){

        var comp = otherCollider.node.getComponent(Enemy);

        log("炮塔碰撞结束:",otherCollider.node);
        log("敌人列表:",this.enemies);

        //如果敌人不在攻击范围内，则删除
        if(this.enemies.indexOf(otherCollider.node) != -1){
            this.enemies.splice(this.enemies.indexOf(otherCollider.node), 1);
        }
    }


    //炮塔碰撞
    onBombContactEnter(selfCollider:Collider2D, otherCollider:Collider2D){

        //如果敌人不在攻击范围内，则添加到攻击范围内
        if(this.enemies.indexOf(otherCollider.node) == -1){
            this.enemies.push(otherCollider.node);
        }

    }

    //炮塔碰撞结束
    onBombContactEnd(selfCollider:Collider2D, otherCollider:Collider2D){

        //如果敌人不在攻击范围内，则删除
        if(this.enemies.indexOf(otherCollider.node) != -1){
            this.enemies.splice(this.enemies.indexOf(otherCollider.node), 1);
        }
    }

    update(deltaTime: number) {

        let pos = "up";

        //箭塔攻击逻辑
        if(this.type===TowerType.ARROW && this.enemies.length > 0 && this.enemies[0] !== null){

            pos = this.soldierTurn(this.enemies[0]);
            
            this.attackTime += deltaTime;

            if (this.attackTime >= this.attackInterval) {
                this.gameManager.createBullet(this.node, this.enemies[0]);
                this.attackTime = 0;
                // 开始播放动画
                this.soldierAnimation(pos, false);
            } else if (this.attackTime >= 0.5) { // 当动画播放完毕后停止
                // 停止动画
                this.soldierAnimation(pos, true);
            }
        }

        // 如果不在攻击状态，确保动画停止
        this.soldierAnimation(pos, true);


        //炮塔攻击逻辑
        if(this.type===TowerType.BOMB && this.enemies.length > 0){
            this.attackTime += deltaTime;
            if (this.attackTime >= this.attackInterval) {
                this.gameManager.createBullet(this.node, this.enemies[0]);
                this.attackTime = 0;
            }
        }


    }

    //显示升级选择界面
    showUpdate() {
        this.node.children[0].active = true;
        this.ringNode.getComponent(Animation).play("tower_update");
    }

    //隐藏升级选择界面
    async hideUpdate() {
        if(this.node.children.length > 1 && this.node.children[0].name == "Ring"){
            this.node.children[0].active = false;
        }
    }

    //点击塔
    onTowerClick() {
        TowerManager.instance.handleTowerClick(this.node);
    }


    //选择了箭塔
    choiceArrowTower(event){

        this.type = TowerType.ARROW;
        var newTower = TowerManager.instance.handleTowerChoice(this.node);

        if(newTower===null){
            this.type = TowerType.NONE;
            //如果升级失败，则清除攻击范围
            if(event.target.getChildByName("Range").getComponent(Graphics)){
                event.target.getChildByName("Range").getComponent(Graphics).clear();
            }
            return;
        }

        this.soundManager.playCoinAudio();
        newTower.getComponent(Tower).type = TowerType.ARROW;
        
        this.hideUpdate();
        
    }


    //选择了炸弹塔
    choiceBombTower(event){

        this.type = TowerType.BOMB;
        var newTower = TowerManager.instance.handleTowerChoice(this.node);

        //如果没升级成
        if(newTower===null){
            //如果升级失败，则清除攻击范围
            this.type = TowerType.NONE;
            if(event.target.getChildByName("Range").getComponent(Graphics)){
                event.target.getChildByName("Range").getComponent(Graphics).clear();
            }
            return;
        }

        this.soundManager.playCoinAudio();
        newTower.getComponent(Tower).type = TowerType.BOMB;
        this.hideUpdate();
    }


    //显示攻击范围
    showAttackRange(event){
        var rangeNode = event.target.getChildByName("Range");
        var graphics = rangeNode.getComponent(Graphics);

        var type = TowerType.NONE;

        if(event.target.name == "Btn1"){
            type = TowerType.ARROW;
        }else if(event.target.name == "Btn2"){
            type = TowerType.BOMB;
        }

        if( graphics == null || type == TowerType.NONE){
            return;
        }

        graphics.clear();
        graphics.fillColor.fromHEX(TOWER_CONFIG[type].color);
        graphics.circle(0,0,TOWER_CONFIG[type].range);
        graphics.fill();
        graphics.stroke();
    }


    //隐藏攻击范围
    hideAttackRange(event){
        //根据不同的塔类型，显示不同的攻击范围
        var rangeNode = event.target.getChildByName("Range");

        if (rangeNode.getComponent(Graphics)) {
            rangeNode.getComponent(Graphics).clear();
        }
    }

    //判断敌人在上面还在下面，用于箭塔上的士兵的转体
    soldierTurn(targetNode:Node){

        if(!targetNode.isValid || targetNode === null){
            return;
        }        

        var enemyPos = targetNode.getWorldPosition();
        var pos = null;
        const angle = Math.atan2(enemyPos.y - this.node.worldPosition.y, enemyPos.x - this.node.worldPosition.x);
        if(angle>0){
            pos =  "up";
        }else if(angle<0){
            pos = "down";
        }

        if (pos == "up") {
            //更换士兵正面的sprite
            this.node.getChildByName("Soldier1").getComponent(Sprite).spriteFrame = this.soldierFront;
            this.node.getChildByName("Soldier2").getComponent(Sprite).spriteFrame = this.soldierFront;
        } else {
            //更换士兵反面的sprite
            this.node.getChildByName("Soldier1").getComponent(Sprite).spriteFrame = this.soldierBack;
            this.node.getChildByName("Soldier2").getComponent(Sprite).spriteFrame = this.soldierBack;
        }
        return pos;
    }


    //士兵射箭动画
    soldierAnimation(pos:string,stop:boolean){

        if (!this.soldier1Animation || !this.soldier2Animation) {
            return;
        }

        if(pos == "up"){
            this.node.getChildByName("Soldier1").getComponent(Animation).play("personUp");
            this.node.getChildByName("Soldier2").getComponent(Animation).play("personUp");
        }else if(pos == "down"){
            this.node.getChildByName("Soldier1").getComponent(Animation).play("personDown");
            this.node.getChildByName("Soldier2").getComponent(Animation).play("personDown");
        }

        if(stop){
            this.node.getChildByName("Soldier1").getComponent(Animation).stop();
            this.node.getChildByName("Soldier2").getComponent(Animation).stop();
        }
    }


    /**
 * 炮塔的准备动画
 */
    bombTowerReadtAni() {
        if (this.type === TowerType.BOMB) {
            this.getComponent(Animation).play("ready");
        }
    }



    testBtn(){
        log("enemies:",this.enemies);
    }
}


